package controlleur;

import entities.question.AbstractQuestion;
import controlleur.util.JsfUtil;
import controlleur.util.PaginationHelper;
import entities.Proposition;
import entities.question.QuestionChoix;
import entities.question.QuestionOuverte;
import entities.question.QuestionUnique;
import facade.AdministrationFacadeLocal;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean (name="questionController")
@SessionScoped
public class QuestionController implements Serializable {

    private AbstractQuestion current;
    private DataModel items = null;
//    @EJB private doaNb.QuestionFacade ejbFacade;
    @EJB
    private AdministrationFacadeLocal ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    private String intitule = ResourceBundle.getBundle("/Parametres").getString("CreateQuestionDefaultIntitule");
    private String type;
    private String[] listeType = {"Choix Multiple","Réponse Unique","Ouverte"};

    // liste des propositions d'une question
    private DataModel dtmPropositions;
    private List<Proposition> listeProposition;
    private Proposition laProposition;
    private String textePropo = ResourceBundle.getBundle("/Parametres").getString("CreatePropositionDefaultTexte");
    private String valeurPropo = ResourceBundle.getBundle("/Parametres").getString("CreatePropositionDefaultValeur");

    private AbstractQuestion laQuestion;


    public QuestionController() {
    }

    public AbstractQuestion getSelected() {
        if (current == null) {
            current = new QuestionOuverte();
//            current = new QuestionChoix();
            selectedItemIndex = -1;
        }
        return current;
    }

    private AdministrationFacadeLocal getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().countQuestion();
                }

                @Override
                public DataModel createPageDataModel() {
                    //return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem()+getPageSize()}));
                    return new ListDataModel(getFacade().findAllQuestion());
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (AbstractQuestion)getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
//        current = new QuestionOuverte();
//        current = new QuestionChoix();
        selectedItemIndex = -1;
        return "ToQuestionCreer";
    }

    public String create() {
        try {
            if ((laQuestion != null) && (laQuestion.getId() > 0)){
                update();
            } else {
                if (getListeType()[2].equals(getType()))
                    laQuestion = new QuestionOuverte();
                else {
                    if (getListeType()[0].equals(getType()))
                        laQuestion = new QuestionChoix();
                    if (getListeType()[1].equals(getType()))
                        laQuestion = new QuestionUnique();
                }
                laQuestion.setIntitule(getIntitule());
                getFacade().createQuestion(laQuestion);
                // mise à jour de l'id pour pouvoir enregistrer les propositions
                laQuestion.setId(getFacade().getLastIdQuestion());

                if (!getListeType()[2].equals(getType())){
                    for (Proposition p : getListeProposition()) {
                        if (p.getId() <= 0)
                            getFacade().createProposition(p);
                    }
                    laQuestion.setPropositions(getListeProposition());
                    getFacade().editQuestion(laQuestion);
                }
            
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Parametres").getString("QuestionCreated"));
            }
//            return prepareCreate();
            return null;
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Parametres").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (AbstractQuestion)getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            if (!getListeType()[2].equals(getType())){
                    for (Proposition p : getListeProposition()) {
                        if (p.getId() <= 0)
                            getFacade().createProposition(p);
                    }
                laQuestion.setPropositions(getListeProposition());
            }
            
            getFacade().editQuestion(laQuestion);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Parametres").getString("QuestionUpdated"));
            return null;
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Parametres").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (AbstractQuestion)getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
//            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Parametres").getString("QuestionDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Parametres").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().countQuestion();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count-1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
//            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex+1}).get(0);
        }
    }

    public AbstractQuestion getLaQuestion() {
        return laQuestion;
    }

    public void setLaQuestion(AbstractQuestion laQuestion) {
        this.laQuestion = laQuestion;
    }

    public String getIntitule() {
        return intitule;
    }

    public void setIntitule(String intitule) {
        this.intitule = intitule;
    }

    public String[] getListeType() {
        return listeType;
    }

    public void setListeType(String[] listeType) {
        this.listeType = listeType;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    public DataModel getDtmPropositions() {
        if (dtmPropositions == null)
            dtmPropositions = new ListDataModel(new ArrayList<Proposition>());
        return dtmPropositions;
    }

    public void setDtmPropositions(DataModel dtmPropositions) {
        this.dtmPropositions = dtmPropositions;
    }

    public List<Proposition> getListeProposition() {
        if (listeProposition == null)
            listeProposition = new ArrayList<Proposition>();
        return listeProposition;
    }

    public void setListeProposition(List<Proposition> listeProposition) {
        this.listeProposition = listeProposition;
    }

    public Proposition getLaProposition() {
        return laProposition;
    }

    public void setLaProposition(Proposition laProposition) {
        this.laProposition = laProposition;
    }

    public String getTextePropo() {
        return textePropo;
    }

    public void setTextePropo(String textePropo) {
        this.textePropo = textePropo;
    }

    public String getValeurPropo() {
        return valeurPropo;
    }

    public void setValeurPropo(String valeurPropo) {
        this.valeurPropo = valeurPropo;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public String choisirType(ValueChangeEvent event){
        System.out.println(getType());
        return null;
    }

    public SelectItem[] getTypesAvailableSelectMany() {
        return JsfUtil.getSelectItems(Arrays.asList(listeType), false);
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAllQuestion(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAllQuestion(), true);
    }

    public String ajouterProposition(){
        getListeProposition().add(new Proposition(getTextePropo(), getValeurPropo()));
        dtmPropositions = new ListDataModel(getListeProposition());
        setTextePropo(ResourceBundle.getBundle("/Parametres").getString("CreatePropositionDefaultTexte"));
        setValeurPropo(ResourceBundle.getBundle("/Parametres").getString("CreatePropositionDefaultValeur"));
        return null;
    }

    public String retirerProposition(){
        laProposition = (Proposition)getDtmPropositions().getRowData();
        getListeProposition().remove(laProposition);
        dtmPropositions = new ListDataModel(getListeProposition());
        return null;
    }

    @FacesConverter(forClass=AbstractQuestion.class)
    public static class QuestionControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            QuestionController controller = (QuestionController)facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "questionController");
            return controller.ejbFacade.findQuestion(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof AbstractQuestion) {
                AbstractQuestion o = (AbstractQuestion) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: "+QuestionController.class.getName());
            }
        }

    }

}
